package com.googlecode.dgwt.client.dojox.data.model;

import com.googlecode.dgwt.client.dojo.data.model.StoreColumn;
import com.googlecode.dgwt.client.dojo.data.model.StoreColumnBase;
import com.googlecode.dgwt.client.dojo.data.model.StoreModel;
import com.googlecode.dgwt.client.dojo.reflect.BeanInfo;
import com.googlecode.dgwt.client.dojo.reflect.HasBeanInfo;
import com.googlecode.dgwt.client.dojox.data.base.EmptyStore;
import com.googlecode.dgwt.client.dojox.data.model.base.DataModelBase;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class ProxyModel<Item> extends DataModelBase<Item, ProxyColumn<Item,?>> implements HasBeanInfo<Item> {
    
    private StoreModel<Item,StoreColumn<Item, ?>> targetModel;
        
    protected ProxyModel(){
        setTargetModel(EmptyStore.<Item>getEmptyModel());
    }
    
    public ProxyModel(StoreModel<Item, ? extends StoreColumn<Item,?>> model) {
        super(model.getColumns().size());
        setTargetModel(model);
    }
    
    @SuppressWarnings("unchecked")
    public ProxyModel(StoreModel<Item, ? extends StoreColumnBase<Item,?>> model, boolean copyColumns) {
        super(model.getColumns().size());
        setTargetModel(model);
        if (copyColumns) {
            for (StoreColumnBase<Item,?> column : model.getColumns()) {
                getColumns().add(new ProxyColumn(column));
            }
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public BeanInfo<Item> getBeanInfo() {
        if (getTargetModel() instanceof HasBeanInfo) {
            return ((HasBeanInfo<Item>)getTargetModel()).getBeanInfo();
        }
        return null;
    }

    @Override
    public Item createItem() {
        return getTargetModel().createItem();
    }

    public StoreModel<Item,StoreColumn<Item, ?>> getTargetModel() {
        return targetModel;
    }

    @SuppressWarnings("unchecked")
    protected void setTargetModel(StoreModel<Item, ? extends StoreColumn<Item, ?>> targetModel){
        this.targetModel = (StoreModel<Item, StoreColumn<Item, ?>>) targetModel;
    }
    
}
